<template>
  <div>
    <div>
      <mt-field style="margin-left:-6px;border-top:0 solid " label="*申请部门:">
        <span style="color:#000;display:inline-block;text-align:right" @click="getorglist">{{ chouseval }}</span>
      </mt-field>
    </div>
    <mt-popup v-model="popupVisible22" position="bottom" class="mint-popup" style="width:100%">
      <mt-picker :close-on-click-modal='false' :slots="dataList" :visible-item-count="5" :show-toolbar="true" value-key="orgname" @change="onDateChange" @visible-change="closepicker">
        <mt-button class="sure" style="display:block;position: absolute;right: 0px;" @click="handleConfirm2">确认</mt-button>
      </mt-picker>
    </mt-popup>
  </div>
</template>
<script>
export default {
  data () {
    return {
      popupVisible22: false,
      chouseval: '',
      returnval: {},
      dataList: [
        {
          flex: 1,
          values: [],
          className: 'slot1',
          textAlign: 'left'
        }
      ],
      ts: this.newStore(),
      handler: function (e) {
        e.preventDefault()
      },
    }
  },

  watch: {
    //picker关闭没有回调函数，所以侦听该属性替代
    popupHandleVisible (val) {
      //alert('0909')
      console.log(val, 'val');
      if (val) {
        this.closeTouch()
      } else {
        this.openTouch()
      }
    }
  },
  mounted () {
    this.chouseval = '请选择申请部门'
  },
  methods: {

    closepicker (val) {
      console.log(val, 'val');

      if (val) {
        this.closeTouch()
      } else {
        this.openTouch()
      }

    },
    closeTouch () {
      document.getElementsByTagName('body')[0].addEventListener('touchmove', this.handler, { passive: false })//阻止默认事件
    },
    openTouch () {
      document.getElementsByTagName('body')[0].removeEventListener('touchmove', this.handler, { passive: false })//打开默认事件
    },
    // 获取所在部门
    getorglist () {
      document
        .getElementsByTagName('body')[0]
        .addEventListener('touchmove', this.handler, { passive: false })
      this.orgArr = []
      const req = {
        handle:
          '45EE8FEFE87870C53A0536D8566DA8C965BCDC96F0F3659D3ACB0B4D9576CA03',
        token: localStorage.getItem('token'),
        suporgid: this.suporgid
      }
      this.spost(this.ts, '/mainservlet', req).then(ts => {
        // this.orglist = ts.d.data.operation1;
        // this.suporgid = ts.d.data.operation2[0].hash.suporgid;
        const orglist = ts.d.data.operation1
        const suporgid = ts.d.data.operation2[0].hash.suporgid

        const orgsobj = this.orgobjputfirst(orglist, suporgid)
        const orgarray = this.orgobjgetarray(orgsobj)

        // console.log('orgarray', orgarray);

        const orgarrayfinal = []

        for (let i = 0; i < orgarray.length; i += 1) {
          for (let j = 0; j < orglist.length; j += 1) {
            if (orgarray[i].orgid == orglist[j].hash.orgid) {
              const orgbase = {}
              orgbase.orgid = orglist[j].hash.orgid

              let kongge = ''
              for (let k = 1; k < orgarray[i].level; k += 1) {
                kongge += '>'
              }

              orgbase.orgname = kongge + orglist[j].hash.orgname

              orgarrayfinal.push(orgbase)
            }
          }
        }
        this.orgArr = orgarrayfinal
        this.dataList[0].values = orgarrayfinal
        console.log(this.dataList, '11111')
      })
      this.popupVisible22 = true
    },
    /**
     * 根据生成的对象解析成一个数组，方便显示
     */
    orgobjgetarray (orgsobj) {
      const orgs = []

      this.orgobjgetmin(orgsobj, orgs, 0)
      // console.log(orgs);

      return orgs
    },

    /**
     * 前面
     * @param orgsobj：org全对象
     * @param orgs：org数组
     * @param level：当前级别
     */
    orgobjgetmin (orgsobj, orgs, level) {
      level += 1

      for (const key in orgsobj) {
        const org = { orgid: key, level }

        orgs.push(org)
        this.orgobjgetmin(orgsobj[key], orgs, level)
      }
    },

    /*
     * 初始化方法，先处理完第一级部门再递归（因为分2种情况）
     * orglist:部门全list
     * suporgid：第一级别的orgid
     */
    orgobjputfirst (orglist, suporgid) {
      const orgsobj = {}
      let havesuporgid = false

      // 先判断是否含有suporgid，如果有初始化结束
      for (let i = 0; i < orglist.length; i += 1) {
        if (orglist[i].hash.orgid == suporgid) {
          orgsobj[suporgid] = {}
          havesuporgid = true
          break
        }
      }

      // 如果不包含suporgid，让suporgid下一级部门为第一层
      if (!havesuporgid) {
        for (let i = 0; i < orglist.length; i += 1) {
          if (orglist[i].hash.suporgid == suporgid) {
            orgsobj[orglist[i].hash.orgid] = {}
          }
        }
      }

      //			console.log(orgsobj);
      // 第一层的部门已经存放好了，开始递归遍历下级部门

      for (const minsuporgid in orgsobj) {
        this.orgobjput(orglist, minsuporgid, orgsobj[minsuporgid])
      }

      // 处理完毕返回结果
      return orgsobj
    },

    /*
     * 遍历org下级并放入对象中
     * orglist： 全org数组
     * minsuporgid：要遍历的orgid
     * obj：要放入的对象
     */
    orgobjput (orglist, minsuporgid, obj) {
      for (let i = 0; i < orglist.length; i += 1) {
        if (orglist[i].hash.suporgid == minsuporgid) {
          // 放入新的数据
          obj[orglist[i].hash.orgid] = {}
          // 这里使用递归，再遍历放入下层的，直到没有下级（if条件无法进入为止）
          this.orgobjput(
            orglist,
            orglist[i].hash.orgid,
            obj[orglist[i].hash.orgid]
          )
        }
      }
    },
    onDateChange (picker, values) {
      console.log(picker)
      if (values[0] == undefined) {
        this.chouseval = '请选择申请部门'
      } else {
        this.returnval = values[0]
        this.chouseval = values[0].orgname
      }
    },
    handleConfirm2 () {
      document
        .getElementsByTagName('body')[0]
        .removeEventListener('touchmove', this.handler, { passive: false })
      //console.log(this.$refs.picker.getValues()[0],'2222');

      //this.chouseval = this.$refs.picker.getValues()[0]
      this.popupVisible22 = false
      console.log(this.returnval, 'this.returnval')
      this.$emit('update:getspl', this.returnval.orgid)
    }
  }
}
</script>
<style scoped>
</style>
